package com.demo01;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Demo05 {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //1.获取Class对象
        Class c = Person.class;
        //2.获取构造方法
        Constructor con = c.getConstructor(String.class, int.class, String.class);
        //3.通过构造方法，创建对象
        Object obj = con.newInstance("小明", 20, "福州");
        //4.获取指定的方法
        Method method4 = c.getMethod("method4", String.class);
        //5.执行找到的方法
        //invoke(Object obj, Object... args)
        //obj:执行该方法的对象
        //args:参数
        //@return:该方法的返回值
        Object result = method4.invoke(obj, "method4的参数");
        System.out.println("result = " + result);

        Method method1 = c.getMethod("method1");
        Object result1 = method1.invoke(obj);
        System.out.println("result1 = " + result1);

        Method method5 = c.getDeclaredMethod("method5");
        //开启暴力访问
        method5.setAccessible(true);
        method5.invoke(obj,null);
    }
}
